<?php
namespace Wx\Controller;

use Think\Controller;

class ConfirmController extends BaseController
{

    public $userid;
    public function _initialize()
    {
        date_default_timezone_set('Asia/Shanghai');
        @header('Content-type: text/html;charset=UTF-8');
        vendor('WxPayPubHelper.WxPayPubHelper');
        if (session('oto_userId')) {
            $this->userid = session('oto_userId');
        }
    }

    public function checkPayPWD()
    {

        if (!session('oto_userId')) {
            $this->ajaxReturn(array('status' => -2, 'msg' => '请先登录'));return;
        }

        $info = M('users')->where(array('userId' => session('oto_userId')))->field('loginSecret,userMoney,payPwd')->find();

        if (empty($info['payPwd'])) {
            $this->ajaxReturn(array('status' => -4, 'msg' => '请先设置支付密码'));return;
        }
        $pwd = I('pwd');
        if (md5($pwd . $info['loginSecret']) != $info['payPwd']) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '支付密码错误'));
            return;
        } else {
            $this->ajaxReturn(array('status' => 0));
        }
    }

    public function index()
    {
        //$temp = D('Cart')->getCartInfo();
        // $cartInfo = $temp['cartgoods'];
        //print_r($cartInfo);
        //session("WST_CART",null);
        //print_r(session("WST_CART"));
    }

    public function confirmOrder()
    {
        parent::isLogin();
        $goodsId = (int) I('goodsId');
        $isGroup = I('isGroup');
        $isSeckill = I('isSeckill');
        $addressId = I('addressId');
        //商品ID_属性ID18_324_321_320_秒杀_团购，
        //此处取出该商店商品
        $temp = D('Cart')->getCartInfo()['cartgoods'][I('shopId')];
        $cartInfo = $temp['shopgoods'];

        $this->freeMoney = $temp['deliveryFreeMoney'];

        //print_r(D('Cart')->getCartInfo());
        //重新过滤购物车商品
        if ($isSeckill == 1) {
            //秒杀
            $tempInfo = array();
            foreach ($cartInfo as $k => $v) {
                if ($v['goodsId'] == $goodsId && $v['isSeckill'] == 1) {
                    $daojishi = $this->getTime($v['seckillSetTime']); //倒计时
                    $tempInfo[] = $cartInfo[$k];
                }
            }
            $cartInfo = $tempInfo;
        } else if ($isGroup == 1) {
            //团购
            $tempInfo = array();
            foreach ($cartInfo as $k => $v) {
                if ($v['goodsId'] == $goodsId && $v['isGroup'] == 1) {
                    $daojishi = $this->getTime($v['seckillSetTime']); //倒计时
                    $tempInfo[] = $cartInfo[$k];
                }
            }
            $cartInfo = $tempInfo;
        } else {
            //普通商品
            $tempInfo = array();
            foreach ($cartInfo as $k => $v) {
                if ($v['isSeckill'] == 0 && $v['isGroup'] == 0) {
                    $tempInfo[] = $cartInfo[$k];
                }
            }
            $cartInfo = $tempInfo;

        }
        //print_r($cartInfo);
        $goodsId_attrId = '';
        foreach ($cartInfo as $k => $v) {
            //$arr = [$v['goodsId'],$v['goodsAttrId'],'isSeckill','isGroup'];
            $arr = [$v['goodsId'], $v['goodsAttrId'], $v['isSeckill'], $v['isGroup']];
            $goodsId_attrId[] = implode('_', $arr);
        }
        //print_r($goodsId_attrId);exit;
        $goodsId_attrId = implode(',', $goodsId_attrId);
        //$goodsId_attrId=I('get.g_a');
        if (!$goodsId_attrId) {
            $this->redirect(U('Index/Index', '', 0, 0));
        }
        //默认地址
        $field = "addressId,userName,userPhone,address,areaId1,areaId2,areaId3,lat,lng";
        $map['addressFlag'] = 1;
        $map['isDefault'] = 1;
        $map['userId'] = session('oto_userId');
        $addrInfo = M('user_address')->field($field)->order('isDefault DESC')->where($map)->select();
        //如果存在传参的地址ID 则是重新选择地址
        if ($addressId) {
            $where['addressId'] = $addressId;
            $addrInfo = M('user_address')->where($where)->select();
        }
        // $db = M('areas');
        // foreach ($addrInfo as $k => $v) {
        //     $addrInfo[$k]['province'] = $db->where(array('areaId' => $v['areaId1']))->getField('areaName');
        //     $addrInfo[$k]['city'] = $db->where(array('areaId' => $v['areaId2']))->getField('areaName');
        //     $addrInfo[$k]['area'] = $db->where(array('areaId' => $v['areaId3']))->getField('areaName');
        // }

        $this->time = D('Shop')->serviceTime();
        $lat = $addrInfo[0]['lat'];
        $lon = $addrInfo[0]['lng'];
        $shopInfo = M('shops')->where(['shopId' => I('shopId')])->find();
        $ptm = D("Wx/Search")->getPtDeliveryConfig();
        //计算平台配送费/配送时间
        if ($shopInfo['deliveryType'] == 1 && !empty($ptm)) {
            $lat2 = $shopInfo['latitude'];
            $lon2 = $shopInfo['longitude'];
            $shopInfo['juli'] = D("Wx/Search")->getDistance($lat, $lon, $lat2, $lon2);
            if ($shopInfo['juli']) {
                for ($j = 0; $j < count($ptm); $j++) {
                    if ($shopInfo['juli'] <= $ptm[$j]['go_distance'] * 1000) {
                        $shopInfo['deliveryCostTime'] = $ptm[$j]['go_distance_time2'];
                        $shopInfo['deliveryMoney'] = (float) $ptm[$j]['go_money'];
                        break;
                    }
                    if($shopInfo['juli'] > $ptm[$j]['go_distance'] * 1000 && $j == count($ptm) - 1){
                        $addrInfo = array();
                    }

                }
            }
        }
        $this->shopInfo = $shopInfo;
        $this->uId = session('oto_userId');

        //点击地址信息回调判断
        $param = $_GET;
        $str = '';
        foreach ($param as $k => $v) {
            $str .= ($k . '/' . $v . '/');
        }
        $this->addressUrl = '/Wx/Confirm/conFirmOrder/' . $str;

        //商品信息

//       $this->cartInfo = $cartInfo;
        //       $this->totalMoney = $cartInfo['totalMoney'];
        $this->deliveryMoney = $cartInfo['deliveryMoney'];

        $this->checkOrderInfo($goodsId_attrId);
        session('clearCartGoodsIdAttrId', $goodsId_attrId);
        //print_r($this->info);
        //print_r(session('sortingOrder'));
        $this->assign('daojishi', $daojishi);
        $this->assign('addrInfo', $addrInfo);
        $this->display('xiadan');
    }

    public function getTime($seckillSetTime = 0)
    {
        if ($seckillSetTime == 4) {
            $seckillSetTime = 0;
        } else {
            $seckillSetTime++;
        }
        switch ($seckillSetTime) {
            case 0:$time = '23,59,59';
                break;
            case 1:$time = '08,00,00';
                break;
            case 2:$time = '12,00,00';
                break;
            case 3:$time = '16,00,00';
                break;
            case 4:$time = '20,00,00';
                break;
        }
        $nowDate = date('Y,m,d,', time()) . $time;
        return $nowDate;
    }
    /**
     * 核对订单信息
     */
    public function checkOrderInfo($goodsId_attrId)
    {
        parent::isLogin();
        //$goodsId_attrId商品id_属性ID ','分开
        $g_a_arr = explode(',', $goodsId_attrId);
        session('goods_attr', $g_a_arr);
        if (!session('oto_userId')) {
            $this->redirect(U('index/login'));
            return;
        }
        $mareas = D('Wx/Areas');
        $morders = D('Wx/Orders');
        $mgoods = D('Wx/Goods');
        $maddress = D('Wx/UserAddress');
        $gtotalMoney = 0; //商品总价（去除配送费）
        $totalMoney = 0; //商品总价（含配送费）
        $totalNum = 0; //商品总数
        $totalCnt = 0;

        //购物车信息
        $map['userId'] = session('oto_userId');
        $isCarExists = M('car_session')->where($map)->field('car_session,userId')->find();
        $WST_CART = unserialize($isCarExists['car_session']);
        $shopcat = $WST_CART ? $WST_CART : array();
        $catgoods = array();
        $shopColleges = array();
        $startTime = 0;
        $endTime = 24;

        //去除不在勾选中的购物车订单
        // foreach ($shopcat as $k=>$v){
        //     if(!in_array($k,$g_a_arr)){
        //         unset($shopcat[$k]);
        //     }
        // }
        // print_r($shopcat);die;
        //筛选当前商店的商品
        $gnum = 0;
        foreach ($shopcat as $k => $v) {
            if ($v['shopId'] != I('shopId')) {
                unset($shopcat[$k]);
            }
            //如果是秒杀或者团购，则需要过滤
            if (I('isSeckill') == 1) {
                if ($v['isSeckill'] == 0) {
                    unset($shopcat[$k]);
                }

            } else {
                if ($v['isSeckill'] == 1) {
                    unset($shopcat[$k]);
                }

            }
            if (I('isGroup') == 1) {
                if ($v['isGroup'] == 0) {
                    unset($shopcat[$k]);
                }

                $gnum = $v['cnt'];
            } else {
                if ($v['isGroup'] == 1) {
                    unset($shopcat[$k]);
                }

            }
        }

//print_r($info['cartgoods']);die;

        if (empty($shopcat)) {
            //$this->assign("fail_msg",'不能提交空商品的订单!');
            $this->redirect(U('Wx/Orders/orders', '', '', 0));
            exit();
        }
        // print_r($shopcat);die;
        foreach ($shopcat as $key => $cgoods) {
            $obj = array();
            $temp = explode('_', $key);
            //遍历分别取出商品id和商品属性id
            $obj["goodsAttrId"] = array();
            foreach ($temp as $k => $v) {
                //商品ID_属性ID_秒杀_团购
                if ($k == 0) {
                    $obj["goodsId"] = (int) $v;
                } else {
                    $obj["goodsAttrId"][] = (int) $v;
                }
            }

            //属性ID
            $atId = array_slice($obj["goodsAttrId"], 0, count($obj["goodsAttrId"]) - 2);

            $obj["goodsAttrId"] = implode(',', $obj["goodsAttrId"]);
            $obj["groupId"] = $cgoods['id'] ? $cgoods['id'] : 0;
            //if($cgoods["ischk"]==1){
            //商品信息
            $goods = $mgoods->getGoodsForCheck($obj);
            if ($goods["isBook"] == 1) {
                $goods["goodsStock"] = $goods["goodsStock"] + $goods["bookQuantity"];
            }
            $goods["ischk"] = $cgoods["ischk"];
            $goods["cnt"] = $cgoods["cnt"];
            $goods["goodsAttrId"] = implode(',', $atId);
            $catgoods[$goods["shopId"]]["shopgoods"][] = $goods;
            $catgoods[$goods["shopId"]]["deliveryFreeMoney"] = $goods["deliveryFreeMoney"]; //店铺免运费最低金额
            $catgoods[$goods["shopId"]]["deliveryMoney"] = $goods["deliveryMoney"]; //店铺配送费
            $catgoods[$goods["shopId"]]["deliveryStartMoney"] = $goods["deliveryStartMoney"]; //店铺最低起送费
            //}
            // print_r($catgoods);die;
        }
        // print_r($catgoods);die;
        //商品列表
        $arr['cartgoods'] = $catgoods;
        // print_r($arr);
        $info = $this->sortingOrder($arr, 1);
        foreach ($info['cartgoods'] as $k => $v) {

            //店铺循环
            foreach ($v as $kk => $vv) {
                //店内商品循环
                foreach ($vv as $kkk => $vvv) {
                    if ($vvv['goodsAttrId']) {
//是否属性商品
                        $num = count(explode(',', $vvv['goodsAttrId']));
                        $tempMoney = 0;
                        $vvv['attrName'] = '';
                        //属性商品价格相加
                        for ($i = 0; $i < $num; $i++) {
                            $tempMoney += $vvv[$i]['shopPrice'];
                            $vvv['attrName'] .= "【{$vvv[$i]['attrName']}】";
                        }
                        // $totalMoney+=$tempMoney*$vvv['cnt'];
                        $vvv['shopPrice'] = $tempMoney;
                        $info['cartgoods'][$k][$kk][$kkk] = $vvv;
                        // print_r($info['cartgoods'][$k][$kk][$kkk]);die;
                    }
                }

            }
            //免邮
            if ($v['deliveryFreeMoney'] <= $info['totalMoney']) {
                $info['cartgoods'][$k]['deliveryMoney'] = 0;
            } else {
                $info['cartgoods'][$k]['deliveryMoney'] = $v['deliveryMoney'];
            }

        }

        //待支付的订单分拣好的订单
        session('sortingOrder', $info);
        $this->assign("info", $info);

    }

    //在线支付页面
    public function onlinkPay()
    {
        parent::isLogin();
        $pid = session('payid');
        $payid = isset($pid) ? $pid : I('get.payid');
        $type = M('orders_payid')->where(array('id' => $payid))->getField('type');
        $orderIds = M('orders_payid')->where(array('pid' => $payid))->field('orderId')->select();
        if ($type == 2) {
            $orderIds = M('orders_payid')->where(array('id' => $payid))->field('orderId')->select();
        }
        //获取订单信息
        $orderInfo = M('orders')->where(array('orderId' => $orderIds[0]['orderId']))->field('payType')->select();
        //微信o支付或者积分  购买积分商品 隐藏余额支付
        if ($orderInfo[0]['payType'] == 4) {
            # code...
            $this->assign('payType', 'scoreGoods');

        }
        // dump($payid);
        // dump($orderIds);
        // dump($type);
        // exit();
        $userPhoto = M('users')->where(array('userId' => session('oto_userId')))->getField('userPhoto');
        $shopName = M('sys_configs')->where(array('configId' => 1))->getField('fieldValue');
        $this->assign('orderids', $payid);
        //用户余额
        $info = M('users')->where(array('userId' => session('oto_userId')))->field('userMoney,payPwd')->find();

        //下单付款
        if ($type == 1) {

            $orderIds = M('orders_payid')->where(array('pid' => $payid))->field('orderId')->select();
            $ids = '';
            foreach ($orderIds as $K => $v) {
                $ids .= $v['orderId'] . ',';
            }
            $ids = rtrim($ids, ',');
            $orderNos = M('orders')->where(array('orderId' => array('in', $ids)))->field('orderNo')->select();
            $Nos = '';
            foreach ($orderNos as $k => $v) {
                $Nos .= $v['orderNo'] . ',';
            }
            $Nos = rtrim($Nos, ',');
            $needPay = M('orders')->where(array('orderId' => array('in', $ids)))->sum('needPay');

        } else {
            //充值
            $needPay = M('top_up')->where(array('topupNo' => $payid))->getField('money');
        }
        $this->assign('type', $type);
        $this->assign('needPay', $needPay);

        $this->assign('payid', $payid);
        $this->assign('orderId', $orderIds[0]['orderId']);
        $payPwd = $info['payPwd'] ? 1 : 0;
        $this->assign('pwd', $payPwd);
        $this->assign('balance', $info['userMoney']);
        $this->assign('userPhoto', $userPhoto);
        $this->assign('shopName', $shopName);
        $this->assign('openId', 0);
        //微信支付
        /*
        if (strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') == true){
        $config = M('Payments')->field('payName,payConfig')->where(array('payCode' => 'weixin', 'enabled' => 1))->find();
        $payConfig = json_decode($config['payConfig']);
        $appId = $payConfig->appId;
        $app_secret = $payConfig->appsecret;
        if (!isset($_GET['code'])){

        $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/wx/Confirm/onlinkPay/payid/'.$payid;
        $url = \Pingpp\WxpubOAuth::createOauthUrlForCode($appId,$redirect_url);
        if ($config) {
        Header("Location: $url");
        }

        }else{
        $code = $_GET['code'];

        $openId = \Pingpp\WxpubOAuth::getOpenid($appId,$app_secret,$code);
        $this->assign('openId',$openId);

        }

        }
         */

        session('payid', null);
        $this->display('onlinkPay');
    }

    /**
     * 核对商品信息
     */
    public function checkGoodsStock()
    {
        parent::isLogin();
        $consigneeId = (int)I('consigneeId');
        $shopId = (int)I('shopId');
        if(empty($consigneeId)){
            $this->ajaxReturn(array('status'=>-5));
            return;
        }
        $addrInfo = M("user_address")->where("addressId = {$consigneeId}")->find();
        $lat = $addrInfo['lat'];
        $lon = $addrInfo['lng'];
        $shopInfo = M('shops')->where(['shopId' => $shopId])->find();
        $ptm = D("Wx/Search")->getPtDeliveryConfig();
        //计算平台配送费/配送时间
        if ($shopInfo['deliveryType'] == 1 && !empty($ptm)) {
            $lat2 = $shopInfo['latitude'];
            $lon2 = $shopInfo['longitude'];
            $shopInfo['juli'] = D("Wx/Search")->getDistance($lat, $lon, $lat2, $lon2);
            if ($shopInfo['juli']) {
                for ($j = 0; $j < count($ptm); $j++) {
                    if ($shopInfo['juli'] <= $ptm[$j]['go_distance'] * 1000) {
                        $noRange = true;
                        break;
                    }
                    if($shopInfo['juli'] > $ptm[$j]['go_distance'] * 1000 && $j == count($ptm) - 1){
                        $noRange = false;
                        break;
                    }
                }
            }
        }
        if ($noRange) {
            //有商品不在配送范围
            $this->ajaxReturn(array('status' => -6));
            return;
        }
        $cartInfo = session('sortingOrder');
        $arr = $this->checkStotck($cartInfo);
        $this->ajaxReturn($arr);
    }

    /**
     * 核对商品信息(弃用)
     */
    public function checkGoodsStock2()
    {
        parent::isLogin();
        $province = I('province');
        $city = I('city');
        $area = I('area');
        $community = I('community');
        if (empty($province) || empty($city) || empty($area)) {
            $this->ajaxReturn(array('status=>'-5));
            return;
        }
        $g_a_arr = session('goods_attr');
        //判断 是否在配送范围
        $goodsIds = '';
        foreach ($g_a_arr as $k => $v) {
            $tmp = explode('_', $v);
            $goodsIds .= $tmp[0] . ',';
        }
        $goodsIds = rtrim($goodsIds, ',');
        $goodsIds = array_unique(explode(',', $goodsIds));
        $noRange = '';
        foreach ($goodsIds as $k => $v) {
            if (!$this->range($area, $community, $v)) {
                $noRange .= $v . ',';
            }
        }
        $noRange = rtrim($noRange, ',');
        if ($noRange) {
            //有商品不在配送范围
            $this->ajaxReturn(array('status' => -6, 'data' => $noRange));
            return;
        }
        $cartInfo = session('sortingOrder');

        $arr = $this->checkStotck($cartInfo);
        // echo M()->getLastSql();
        // dump($arr);die;
        $this->ajaxReturn($arr);

    }

    //配送范围
    public function range($area, $community, $goodsId)
    {
        parent::isLogin();
        $shopid = M('goods')->where(array('goodsId' => $goodsId))->getField('shopId');
        if ($community) {
            $range = M('shops_communitys')->field('communityId')->where(array('shopId' => $shopid, 'communityId' => $community))->find();
            if (!$range) {
                //不在配送范围
                return false;
            }
        } else if ($area) {
            //区级配送范围
            $range = M('shops_communitys')->field('areaId3')->where(array('shopId' => $shopid, 'areaId3' => $area))->find();
            if (!$range) {
                //不在配送范围
                return false;
            }
        }
        return true;
    }

    /**
     * 提交订单信息
     *
     */
    public function submitOrder()
    {
        parent::isLogin();
        $goodsmodel = D('Wx/Goods');
        $morders = D('Wx/Orders');
        $totalMoney = 0;
        $totalCnt = 0;
        $userId = session('oto_userId');
        //收件人
        $consigneeId = (int) I("consigneeId");
        //支付方式
        $payway = (int) I("payway");
        //isself是否送货上门，0是，1自提
        $isself = (int) I("isself");
        //是否需要发票
        $needreceipt = (int) I("needreceipt", 0);

        $orderunique = I("orderunique");

        //读取选择的购物车信息
        $map['userId'] = session('oto_userId');
        $isCarExists = M('car_session')->where($map)->field('car_session,userId')->find();
        $WST_CART = unserialize($isCarExists['car_session']);
        $shopcat = $WST_CART ? $WST_CART : array();
        //去除不在勾选中的购物车订单
        // $g_a_arr= session('goods_attr');
        // foreach ($shopcat as $k=>$v){
        //     if(!in_array($k,$g_a_arr)){
        //         unset($shopcat[$k]);
        //     }
        // }
        //dump( $shopcat);die;
        $catgoods = array();
        if (empty($shopcat)) {
            //购物车已经为空
            $this->ajaxReturn(array('status' => 1, 'msg' => '订单提交成功'));
        } else {

            //整理及核对购物车数据
            //$paygoods = session('WST_PAY_GOODS');
            //dump($paygoods);die;
            foreach ($shopcat as $key => $cgoods) {
                //分开商品id和属性id
                $temp = explode('_', $key);
                $goodsId = (int) $temp[0];
                $goodsAttrId = array();
                foreach ($temp as $k => $v) {
                    if ($k != 0) {
                        $goodsAttrId[] = (int) $v;
                    }
                }

                if (in_array($goodsId, $paygoods)) {

                    $goods = $goodsmodel->getGoodsSimpInfo($goodsId, $goodsAttrId);
                    //核对商品是否符合购买要求
                    if (empty($goods)) {
                        $this->ajaxReturn(array('status' => -1, 'msg' => '对不起，商品' . $goods['goodsName'] . '不存在!'));
                        exit();
                    }
                    if ($goods['goodsStock'] <= 0) {
                        $this->ajaxReturn(array('status' => -2, 'msg' => '对不起，商品' . $goods['goodsName'] . '库存不足!'));
                        exit();
                    }
                    if ($goods['isSale'] != 1) {
                        $this->ajaxReturn(array('status' => -3, 'msg' => '对不起，商品库' . $goods['goodsName'] . '已下架!'));
                        exit();
                    }
                    $goods["cnt"] = $cgoods["cnt"];
                    $totalCnt += $cgoods["cnt"];
                    //商品价格由多个属性shopPrice相加而成
                    $prices = 0;
                    foreach ($goods['attrs'] as $kk => $price) {
                        $prices += $price['shopPrice'];
                    }
                    if ($prices != 0) {
                        $shopPrice = $prices;
                    } else {
                        $shopPrice = $cgoods['shopPrice'];
                    }
                    //所有店铺商品总价
                    $totalMoney += $goods["cnt"] * $shopPrice;
                    $catgoods[$goods["shopId"]]["shopgoods"][] = $goods;
                    $catgoods[$goods["shopId"]]["deliveryFreeMoney"] = $goods["deliveryFreeMoney"]; //店铺免运费最低金额
                    $catgoods[$goods["shopId"]]["deliveryMoney"] = $goods["deliveryMoney"]; //店铺免运费最低金额
                    $catgoods[$goods["shopId"]]["totalCnt"] = $catgoods[$goods["shopId"]]["totalCnt"] + $cgoods["cnt"];
                    $catgoods[$goods["shopId"]]["totalMoney"] = $catgoods[$goods["shopId"]]["totalMoney"] + ($goods["cnt"] * $shopPrice);
                }
            }

            foreach ($catgoods as $key => $cshop) {
                if ($cshop["totalMoney"] < $cshop["deliveryFreeMoney"]) {
                    if ($isself == 0) {
                        $totalMoney = $totalMoney + $cshop["deliveryMoney"];
                    }
                }
            }

            $payway = 1; //默认在线支付，0为货到付款

            $ordersInfo = $morders->addOrders($userId, $consigneeId, $payway, $needreceipt, $catgoods, $orderunique, $isself);
            // if(I('isGroup')==1){
            //      $time = time();
            //      //团购商品信息
            //      $group_info=  M('goods_group')
            //                  ->field('startTime,endTime,groupMaxCount,id')
            //                  ->where([
            //                      'shopId'=>I('shopId'),
            //                      'goodsId'=>I('goodsId'),
            //                      'groupStatus'=>1,
            //                      'startTime'=>['lt',$time],
            //                      'endTime'=>['gt',$time]
            //                      ])
            //                  ->find();
            //      //该用户是否达到购买上限
            //      if($group_info){
            //          $re  = M('orders o')
            //                 ->join("INNER JOIN __ORDER_GOODS__ g on o.orderId = g.orderId and goodsGroupId = '".$group_info['id']."' ")
            //                 ->where([
            //                      'userId'=>session('oto_userId'),
            //                      'createTime'=>['between',[date('Y-m-d H:i:s',$group_info['startTime']), date('Y-m-d H:i:s',$group_info['endTime'])]]

            //                  ])
            //                 ->getField('sum(goodsNums)')
            //                 ;
            //          if($re+$gnum >= $group_info['groupMaxCount']){

            //          }

            //      }else{
            //      }
            //  }
            //结算后清空所选的购物车信息
            $newcart = array();
            $g_a_arr = session('goods_attr');
            foreach ($shopcat as $key => $cgoods) {
                if (!in_array($key, $g_a_arr)) {
                    $newcart[$key] = $cgoods;
                }
            }
            if (empty($newcart)) {
                // M('car_session')->where($map)->delete();
            } else {
                //$isCarExists=M('car_session')->where($map)->save(array('car_session'=>serialize($newcart)));
            }
            $orderNos = $ordersInfo["orderNos"];
            // $this->assign("torderIds",implode(",",$ordersInfo["orderIds"]));
            // $this->assign("orderInfos",$ordersInfo["orderInfos"]);
            // $this->assign("isMoreOrder",(count($ordersInfo["orderInfos"])>0)?1:0);
            // $this->assign("orderNos",implode(",",$orderNos));
            // $this->assign("totalMoney",$totalMoney);
            $orderIds = $ordersInfo["orderIds"];

            $this->ajaxReturn(array('status' => 1, 'msg' => '订单提交成功', 'orderIds' => implode(",", $orderIds)));
        }
    }

    //设置支付密码
    public function setPayPwd()
    {
        parent::isLogin();
        $userid = session('oto_userId');
        $pwd = I('pwd');
        if (!is_numeric($pwd) || strlen($pwd) != 6) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '密码必须是6位数字'));
            return;
        }
        $map['userId'] = $userid;
        $loginSecret = M('users')->where($map)->getField('loginSecret');
        $newPwd = md5($pwd . $loginSecret);
        $res = M('users')->where($map)->save(array('payPwd' => $newPwd));
        if ($res) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '支付密码设置成功'));
        } else {
            $this->ajaxReturn(array('status' => -2, 'msg' => '请稍候重试'));
        }

    }
    //全额支付
    public function balancePay()
    {
        parent::isLogin();
        $info = M('users')->where(array('userId' => session('oto_userId')))->field('loginSecret,userMoney,payPwd')->find();
        $pwd = I('pwd');
        $payid = I('orderids');

        $order_id = M('orders_payid')->where(array('pid' => $payid))->field('orderId')->select();
        $orderids = '';
        foreach ($order_id as $K => $v) {
            $orderids .= $v['orderId'] . ',';
        }
        $orderids = rtrim($orderids, ',');

        $ispayInfo = M('orders')->where(array('orderId' => array('in', $orderids)))->field('isPay,orderNo,orderId,shopId,needPay,orderType')->select();
        $ispay = true;
        $orderNos = '';
        foreach ($ispayInfo as $k => $v) {
            $orderNos .= $v['orderNo'] . ',';
            if ($v['isPay'] == 1) {
                $ispay = false;
            }
        }
        $orderNos = trim($orderNos, ',');
        if (!$ispay) {
            $this->ajaxReturn(array('status' => -4, 'msg' => '订单状态已经改变'));
            return;
        }
        $needPay = M('orders')->where(array('orderId' => array('in', $orderids)))->sum('needPay');
        if (md5($pwd . $info['loginSecret']) != $info['payPwd']) {
            $this->ajaxReturn(array('status' => -2, 'msg' => '支付密码错误'));
            return;
        }
        if ($needPay > $info['userMoney']) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '余额不足'));
            return;
        }
        M()->startTrans();
        $saveData['isPay'] = 1;
        $saveData['orderStatus'] = 0;
        $saveData['paytime'] = time();
        $saveData['payType'] = 3; //余额支付
        $res = M('orders')->where(array('orderId' => array('in', $orderids)))->data($saveData)->save();
        //操作用户金额
        $A = M('users')->where(array('userId' => session('oto_userId')))->setDec('userMoney', $needPay);
        //余额变动记录
        $B = true;
        $balance = $info['userMoney'];
        foreach ($ispayInfo as $k => $v) {
            $balance = $balance - $v['needPay'];
            $tempRes = $this->moneyRecord(1, $v['needPay'], $v['orderNo'], 0, session('oto_userId'), $balance, '', 0);
            if (!$tempRes) {
                $B = false;
            }
        }
        //积分变动记录->移到交易成功后
        // $C=M('users')->where(array('userId'=>session('oto_userId')))->setInc('userScore',floor($needPay));

        // $D=$this->scoreRecord(1,$needPay,$orderNos,1,session('oto_userId'));

        $E = $this->payRecord(0, $orderNos, time(), '', $needPay, session('oto_userId'), 0, '', '', '');

        //操作库存
        $ogField = "goodsId,goodsNums,goodsAttrId";
        // $order_goods=M('order_goods')->where(array('orderId'=>array('in',$orderids)))->select();
        $order_goods = M('order_goods')->join('as g left join oto_orders o on o.orderId=g.orderId')->where(array('g.orderId' => array('in', $orderids)))->field('o.orderType,g.*')->select();
        $goodsDB = M('goods');
        $attrDB = M('goods_attributes');
        $seckillDB = M('goods_seckill');
        $stock = true;
        foreach ($order_goods as $k => $v) {
            $goodsRes = $goodsDB->where(array('goodsId' => $v['goodsId']))->setDec('goodsStock', $v['goodsNums']);
            if ($v['goodsAttrId']) {
                $attrRes = $attrDB->where(array('id' => array('in', $v['goodsAttrId'])))->setDec('attrStock', $v['goodsNums']);
                if (!$goodsRes || !$attrRes) {
                    $stock = false;
                }
            }
            if (!$goodsRes) {
                $stock = false;
            }
            //秒杀
            if ($v['orderType'] == 2) {
                $seckillRes = $seckillDB->where(array('goodsId' => $v['goodsId']))->setDec('seckillStock', $v['goodsNums']);
                if (!$seckillRes) {
                    $stock = false;
                }
            }
        }
        if (!$stock) {
            $this->ajaxReturn(array('status' => -3, 'msg' => '支付失败'));
            M()->rollback();
            return;
        }
//        foreach($ispayInfo as $k2=>$v2){
        //            if($v2['orderType']==2){
        //                $goods  = M('order_goods')->where(array('orderId'=>$v2['orderId']))->field('goodsId,goodsNums')->select();
        //                foreach ($goods as $key3=>$value3){
        //                    M('goods_seckill')->where(array('goodsId'=>$value3['goodsId'],'goodsSeckillStatus'=>1,'seckillStatus'=>1))->setDec('seckillStock',$value3['goodsNums']);
        //                }
        //
        //            }
        //        }

        //操作库存结束

        if ($res && $A && $B && $E) {
            M()->commit();
            //订单日志记录
            $morm = M('order_reminds');
            $mlogo = M('log_orders');
            foreach ($ispayInfo as $k => $v) {
                $data = array();
                $data["orderId"] = $v['orderId'];
                $data["logContent"] = '付款成功';
                $data["logUserId"] = session('oto_userId');
                $data["logType"] = 0;
                $data["logTime"] = date('Y-m-d H:i:s');
                $mlogo->add($data);

                //建立订单提醒
                $data = array();
                $data["orderId"] = $v['orderId'];
                $data["shopId"] = $v['shopId'];
                $data["userId"] = session('oto_userId');
                $data["userType"] = 0;
                $data["remindType"] = 0;
                $data["createTime"] = date("Y-m-d H:i:s");
                $morm->add($data);
            }
            $this->ajaxReturn(array('status' => 0, 'msg' => '支付成功'));

        } else {
            M()->rollback();
            $this->ajaxReturn(array('status' => -3, 'msg' => '支付失败'));
        }
    }

    // 金额操作记录
    /**
     * 构造函数
     * @param $type 操作类型,1下单，2取消订单，3充值，4提现,5订单无效
     * @param $money 金额
     * @param $orderNo 订单编号或者充值ID
     * @param $IncDec 余额变动 0为减，1加
     * @param $userid 用户ID
     * @param $balance 余额
     * @param $remark 其它备注信息
     */
    public function moneyRecord($type = '', $money = 0, $orderNo = '', $IncDec = '', $userid = 0, $balance = 0, $remark = '', $payWay = 0)
    {
        $db = M('money_record');
        $data['type'] = $type;
        $data['money'] = $money;
        $data['time'] = time();
        $data['ip'] = get_client_ip();
        $data['orderNo'] = $orderNo;
        $data['IncDec'] = $IncDec;
        $data['userid'] = $userid;
        $data['balance'] = $balance;
        $data['remark'] = $remark;
        $data['payWay'] = $payWay;
        $res = $db->add($data);
        return $res;
    }

    // 积分操作记录
    /**
     * 构造函数
     * @param $type 1购物，2取消订单，3充值，4订单无效，5活动,6评价订单
     * @param $score 积分
     * @param $shopid 店铺ID
     * @param $orderid 订单ID或者充值ID
     * @param $IncDec 积分变动0为减，1加
     * @param $userid 用户ID
     * @param $totalscore 用户剩余总积分
     */
    public function scoreRecord($type = '', $payMoney = 0, $orderNo = '', $IncDec = '', $userid = 0)
    {
        $score = floor($payMoney);
        if ($score <= 0) {
            return 1;
        }
        $totalscore = M('users')->where(array('userId' => $userid))->getField('userScore');
        $db = M('score_record');
        $data['score'] = $score;
        $data['type'] = $type;
        $data['time'] = time();
        $data['ip'] = get_client_ip();
        $data['orderNo'] = $orderNo;
        $data['IncDec'] = $IncDec;
        $data['userid'] = $userid;
        $data['totalscore'] = $totalscore;
        $res = $db->add($data);
        return $res;
    }
    // 支付记录
    /**
     * 构造函数
     * @param $payType 支付类型 0余额支付，1支付宝，2微信
     * @param $orderNo 订单编号
     * @param $payTime 付款时间
     * @param $out_trade_no 第三方返回的流水号
     * @param $payMoney 金额
     * @param $userId 用户ID
     * @param $type 0订单，1充值
     * @param $notify_id 通知ID
     * @param $notify_time 通知时间
     * @param $buyer_email 支付宝帐号或者微信OPENID
     * */
    public function payRecord($payType = 0, $orderNo, $payTime, $out_trade_no, $payMoney, $userId, $type = 0, $notify_id, $notify_time, $buyer_email)
    {
        $data['payType'] = $payType; //支付类型 0余额支付，1支付宝，2微信
        $data['orderNo'] = $orderNo;
        $data['payTime'] = $payTime;
        $data['out_trade_no'] = $out_trade_no;
        $data['payMoney'] = $payMoney;
        $data['userId'] = $userId;
        $data['type'] = $type;
        $data['notify_id'] = $notify_id;
        $data['notify_time'] = $notify_time;
        $data['buyer_email'] = $buyer_email;
        $db = M('pay_record');
        $res = $db->add($data);
        return $res;
    }

    public function notify()
    {
        $log_name = "Public/hey.txt"; //log文件路径
        //使用通用通知接口
        $notify = new \Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);
        $resultArr = $notify->data;
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == false) {
            $this->logResult($log_name, "不通过:\n" . $xml . "\n");
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
        }

        $returnXml = $notify->returnXml();
        //echo $returnXml;
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //以log文件形式记录回调信息
        //         $log_ = new Log_();

        //$this->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");

        if ($notify->checkSign() == true) {

            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                $this->logResult($log_name, "【通信出错】:\n" . $xml . "\n");
            } elseif ($notify->data["result_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                $this->logResult($log_name, "【业务出错】:\n" . $xml . "\n");
            } else {
                M()->startTrans();
                $tradeNo = $resultArr['transaction_id']; //流水号
                $payMoney = $resultArr['total_fee'] / 100;
                $out_trade_no_text = $resultArr['out_trade_no'];
                $temp = explode('_', $out_trade_no_text);
                $out_trade_no = $temp[1];

                $notify_id = '';
                $time = strtotime($resultArr['time_end']);
                $notify_time = date('Y-m-d H:i:s', $time);
                $buyer_email = $resultArr['openid']; // 买家帐号

                //判断是订单付款还是充值
                $type = M('orders_payid')->where(array('id' => $out_trade_no))->getField('type'); //1订单，2充值

                //订单付款
                if ($type == 1) {

                    $order_id = M('orders_payid')->where(array('pid' => $out_trade_no))->field('orderId')->select();

                    $orderids = '';
                    foreach ($order_id as $K => $v) {
                        $orderids .= $v['orderId'] . ',';
                    }
                    $orderids = rtrim($orderids, ',');
                    $ispayInfo = M('orders')->where(array('orderId' => array('in', $orderids)))->field('userId,isPay,orderNo,orderId,shopId,needPay')->select();
                    $ispay = false;
                    foreach ($ispayInfo as $k => $v) {
                        if ($v['isPay'] == 1) {
                            $ispay = true;
                        }
                    }
                    //已经付过
                    if ($ispay) {
                        echo 'SUCCESS';return;
                    }

                    $orderNos = '';
                    foreach ($ispayInfo as $k => $v) {
                        $orderNos .= $v['orderNo'] . ',';
                        if ($v['isPay'] == 1) {
                            $ispay = false;
                        }
                    }
                    $orderNos = trim($orderNos, ',');

                    $saveData['isPay'] = 1;
                    $saveData['orderStatus'] = 0;
                    $saveData['paytime'] = time();
                    $saveData['payType'] = 2; //微信支付
                    $map['orderId'] = array('in', $orderids);
                    $res = M('orders')->where($map)->data($saveData)->save();

                    $userId = $ispayInfo[0]['userId'];
                    if (!$userId) {
                        echo 'SUCCESS';return;
                    }
                    // $this->log_result($log_name,"【用户ID】:\n".$userId."\n");
                    $userMoney = M('users')->where(array('userId' => $userId))->getField('userMoney');
                    //积分变动记录->移到交易成功后
                    // $C=M('users')->where(array('userId'=>session('oto_userId')))->setInc('userScore',floor($needPay));

                    // $D=$this->scoreRecord(1,$payMoney,$orderNos,1,$userId);
                    //$this->log_result($log_name,"【操作积分】:\n".$D."\n");

                    $E = $this->payRecord(0, $orderNos, time(), $tradeNo, $payMoney, $userId, 0, '', $notify_time, $buyer_email);

                    $F = $this->moneyRecord(1, $payMoney, $orderNos, 0, $userId, $userMoney, '', 2);

                    //$this->log_result($log_name,"【操作付款记录】:\n".$E."\n");
                    //操作库存
                    $ogField = "goodsId,goodsNums,goodsAttrId";
                    $order_goods = M('order_goods')->where(array('orderId' => array('in', "$orderids")))->select();
                    $goodsDB = M('goods');
                    $attrDB = M('goods_attributes');
                    $stock = true;
                    foreach ($order_goods as $k => $v) {
                        $goodsRes = $goodsDB->where(array('goodsId' => $v['goodsId']))->setDec('goodsStock', $v['goodsNums']);
                        if ($v['goodsAttrId']) {
                            $attrRes = $attrDB->where(array('id' => array('in', $v['goodsAttrId'])))->setDec('attrStock', $v['goodsNums']);
                            if (!$goodsRes || !$attrRes) {
                                $stock = false;
                            }
                        }
                        if (!$goodsRes) {
                            $stock = false;
                        }
                    }
                    // $this->log_result($log_name,"【操作库存】:\n".$stock."\n");
                    if (!$stock) {
                        M()->rollback();
                        echo 'FAIL';
                        return;
                    }
                    //操作库存结束
                    if ($res && $E && $F) {
                        //订单日志记录
                        $morm = M('order_reminds');
                        $mlogo = M('log_orders');
                        foreach ($ispayInfo as $k => $v) {
                            $data = array();
                            $data["orderId"] = $v['orderId'];
                            $data["logContent"] = '付款成功';
                            $data["logUserId"] = $userId;
                            $data["logType"] = 0;
                            $data["logTime"] = date('Y-m-d H:i:s');
                            $mlogo->add($data);

                            //建立订单提醒
                            $data = array();
                            $data["orderId"] = $v['orderId'];
                            $data["shopId"] = $v['shopId'];
                            $data["userId"] = $userId;
                            $data["userType"] = 0;
                            $data["remindType"] = 0;
                            $data["createTime"] = date("Y-m-d H:i:s");
                            $morm->add($data);
                        }
                        M()->commit();
                        echo 'SUCCESS';return;
                    } else {
                        M()->rollback();
                        echo 'FAIL';
                        return;
                    }
                } else {
                    //订单充值
                    //判断 是否已经充值成功
                    $isTopUp = M('top_up')->where(array('topupNo' => $out_trade_no))->find();
                    $status = $isTopUp['status'];
                    if ($status == 1) {
                        echo 'SUCCESS';exit;
                    }

                    $userId = $isTopUp['userid'];

                    //充值表
                    $A = M('top_up')->where(array('topupNo' => $out_trade_no))->setField(array('status', 1));
                    $YE = M('users')->where(array('userId' => $userId))->getField('userMoney'); //余额
                    //增加余额
                    $B = M('users')->where(array('userId' => $userId))->setInc('userMoney', $payMoney);
                    //增加积分
                    $B_C = M('users')->where(array('userId' => $userId))->setInc('userScore', floor($payMoney));

                    //余额变动记录
                    $C = $this->moneyRecord(3, $payMoney, $out_trade_no, 1, $userId, $YE, '充值', 2);
                    //积分
                    $D = $this->scoreRecord(3, $payMoney, $out_trade_no, 1, $userId);

                    //付款记录
                    $E = $this->payRecord(2, $out_trade_no, time(), $tradeNo, $payMoney, $userId, 0, '', $notify_time, $buyer_email);

                    if ($A && $B && $B_C && $C && $D && $E) {
                        M()->commit();
                        echo 'SUCCESS';exit;
                    } else {
                        M()->rollback();
                        echo 'FAIL';
                    }

                }

                //此处应该更新一下订单状态，商户自行增删操作
                //$this-> log_result($log_name,"【支付成功】:\n".$xml."\n");
            }

            //商户自行增加处理流程,
            //例如：更新订单状态
            //例如：数据库操作
            //例如：推送支付完成信息
        }
    }

    public function logResult($file, $word)
    {
        $fp = fopen($file, "a");
        flock($fp, LOCK_EX);
        fwrite($fp, "执行日期：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

}
